package com.shz.controller;


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.shz.config.MyPasswordEncoder;
import com.shz.pojo.User;
import com.shz.service.UserService;
import com.shz.utils.JwtTokenUtil;
import com.shz.utils.UserUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.shz.utils.RedisConstants.CACHE_USER_KEY;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yixin
 * @since 2024-06-04
 */
@Api(tags = "用户模块")
@RestController
public class UserController {
    @Resource
    UserService userService;
    @Resource
    StringRedisTemplate stringRedisTemplate;


    @ApiOperation(value = "获取用户个人信息")
    @GetMapping("/user/get")
    public User getUser() {
        User currentUser = UserUtil.getCurrentUser();
        currentUser.setPassword("");
        return currentUser;
    }

    @PutMapping("/user/update")
    public boolean updateUser(String username, String phone) {
        String key = CACHE_USER_KEY + UserUtil.getCurrentUser().getId();
        stringRedisTemplate.delete(key);
        boolean update = userService.update(new UpdateWrapper<User>().set("phone", phone).eq("username", username));
        return update;
    }

    @Resource
    MyPasswordEncoder passwordEncoder;

    @ApiOperation(value = "注册")
 
    @PostMapping("/user/save")
    public boolean addUser(@RequestBody User user) {
        user.setStatus(false);
        if (userService.query().eq("username",user.getUsername()).count()>0) {
            return false;
        }
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        boolean save = userService.save(user);
        return save;
    }


    @Resource
    private JwtTokenUtil jwtTokenUtil;
    @ApiOperation(value = "登录")
    @PostMapping("/login")
    public  HashMap<String, Object> login(String username,String password){
        HashMap<String, Object> map = new HashMap<>();
        final String realToken = jwtTokenUtil.generateToken(username);
        map.put("token", realToken);
        map.put("status", "success");
        return map;
    }

    @ApiOperation(value = "修改用户头像（先调图片上传接口，完整url传进来）")
    @ApiImplicitParam(name = "id", value = "博客id", required = true)
    @PutMapping("/avatar")
    public  Boolean avatar(User user){
      return  userService.updateById(user);

    }

}

